package com.learn.project2.config.shiro.realm;


import com.learn.project2.bean.MarketAdmin;
import com.learn.project2.bean.MarketAdminExample;
import com.learn.project2.bean.MarketPermission;
import com.learn.project2.bean.MarketPermissionExample;
import com.learn.project2.mapper.MarketAdminMapper;
import com.learn.project2.mapper.MarketPermissionMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * @description: shiro 的认证、授权
 * @author zhizhuke
 * @date 2022-01-10 20-09
 * @version 1.0
 */
@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    MarketAdminMapper adminMapper;
    @Autowired
    MarketPermissionMapper permissionMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();

        MarketAdminExample example = new MarketAdminExample();
        example.createCriteria().andUsernameEqualTo(username).andDeletedEqualTo(false);

        List<MarketAdmin> marketAdmins = adminMapper.selectByExample(example);
        MarketAdmin admin = marketAdmins.size() >= 1 ? marketAdmins.get(0) : null;
        String password = null;

        if ("Mac OS X".equals(System.getProperty("os.name")) && admin!=null){

            return new SimpleAuthenticationInfo(admin, token.getPassword(), this.getName());
        }
        if (admin!=null){
            password = admin.getPassword();
        }


        return new SimpleAuthenticationInfo(admin, password, this.getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        MarketAdmin admin  = (MarketAdmin) principalCollection.getPrimaryPrincipal();
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list,admin.getRoleIds());

        MarketPermissionExample example = new MarketPermissionExample();
        example.createCriteria().andRoleIdIn(list);

        List<MarketPermission> marketPermissions = permissionMapper.selectByExample(example);

        List<String> permissions = new ArrayList<>();
        for (MarketPermission marketPermission : marketPermissions) {
            permissions.add(marketPermission.getPermission());
        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);

        return authorizationInfo;
    }


}
